package com.example.demo.sys.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 公用的异常处理类
 * Created by 蔡超 on 2018/10/5.
 */
@Component
@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest,
                                         HttpServletResponse httpServletResponse,
                                         @Nullable Object o, Exception e) {
        String url = httpServletRequest.getRequestURL().toString();
        ModelAndView modelAndView;
        String defaultMsg = "System error";
        //判断是页面请求还是数据请求，可以从request的head中获取，第二种方法，通过约定.json表示数据请求；.page表示页面请求
        if(url.endsWith(".json")){
            if (e instanceof PermissionException) {
                JsonData jsonData = JsonData.failure(e.getMessage());
                modelAndView = new ModelAndView("exception",jsonData.toMap());
            }else{
                JsonData jsonData = JsonData.failure(defaultMsg);
                modelAndView = new ModelAndView("exception",jsonData.toMap());
            }
        }else if(url.endsWith(".page")){
            JsonData jsonData = JsonData.failure(defaultMsg);
            modelAndView = new ModelAndView("exception",jsonData.toMap());
        }else{
            JsonData jsonData = JsonData.failure(defaultMsg);
            modelAndView = new ModelAndView("jsonView",jsonData.toMap());
        }
        log.error("系统异常",e);
        return modelAndView;
    }
}
